import React, { useState, useEffect } from 'react';
import { Button, Form, Input, message } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { register } from '@/services/auth';
import './index.less';

interface RegisterForm {
  username: string;
  password: string;
  password_confirm: string;  // 改为与后端一致
  email: string;
  phone: string;
  nickname?: string;
}

const Register: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  // 添加键盘事件监听
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.key === 'Enter') {
        form.submit();
      }
    };
    
    document.addEventListener('keypress', handleKeyPress);
    return () => document.removeEventListener('keypress', handleKeyPress);
  }, [form]);

  const onFinish = async (values: RegisterForm) => {
    setLoading(true);
    try {
      const response = await register(values);
      
      if (response.success) {
        message.success('🎉 注册成功！欢迎加入LogWisdomHub');
        
        // 注册成功后跳转到登录页
        setTimeout(() => {
          history.push('/login');
        }, 1000);
      } else {
        // 处理验证错误
        if (response.errors) {
          Object.keys(response.errors).forEach(field => {
            const errors = response.errors[field];
            if (Array.isArray(errors)) {
              errors.forEach(error => message.error(error));
            } else {
              message.error(errors);
            }
          });
        } else {
          message.error(response.message || '注册失败');
        }
      }
    } catch (error: any) {
      console.error('注册错误详情:', error);
      console.error('错误响应:', error.response);
      console.error('错误数据:', error.response?.data);
      
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('🔧 注册失败，请稍后重试！');
      }
    } finally {
      setLoading(false);
    }
  };

  const goToLogin = () => {
    history.push('/login');
  };

  return (
    <div className="register-container">
      {/* 动态背景 */}
      <div className="register-background">
        <div className="particles"></div>
        <div className="grid-overlay"></div>
      </div>
      
      {/* 主要内容 */}
      <div className="register-content">
        <div className="register-form-wrapper">
          {/* 标题区域 */}
          <div className="register-header">
            <h1 className="register-title">加入我们</h1>
            <p className="register-subtitle">🚀 创建您的LogWisdomHub账户</p>
            <div className="tech-line"></div>
          </div>
          
          {/* 注册表单 */}
          <Form
            form={form}
            name="register"
            className="register-form"
            onFinish={onFinish}
            autoComplete="off"
            size="large"
            layout="vertical"
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入用户名!' },
                { min: 3, message: '用户名至少3个字符!' },
                { max: 30, message: '用户名不能超过30个字符!' },
                { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '用户名只能包含字母、数字和下划线，且必须以字母开头!' }
              ]}
            >
              <Input
                className="register-input"
                prefix={<UserOutlined className="input-icon" />}
                placeholder="输入用户名（3-30个字符）"
              />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱地址!' },
                { type: 'email', message: '请输入有效的邮箱地址!' }
              ]}
            >
              <Input
                className="register-input"
                prefix={<MailOutlined className="input-icon" />}
                placeholder="输入邮箱地址"
              />
            </Form.Item>

            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号码!' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码!' }
              ]}
            >
              <Input
                className="register-input"
                prefix={<PhoneOutlined className="input-icon" />}
                placeholder="输入手机号码"
              />
            </Form.Item>

            <Form.Item
              name="nickname"
            >
              <Input
                className="register-input"
                prefix={<UserOutlined className="input-icon" />}
                placeholder="输入昵称（可选）"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码!' },
                { min: 8, message: '密码至少8个字符!' },
                { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字!' }
              ]}
            >
              <Input.Password
                className="register-input"
                prefix={<LockOutlined className="input-icon" />}
                placeholder="输入密码（至少8位，包含字母和数字）"
              />
            </Form.Item>

            <Form.Item
              name="password_confirm"
              dependencies={['password']}
              rules={[
                { required: true, message: '请确认密码!' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致!'));
                  },
                }),
              ]}
            >
              <Input.Password
                className="register-input"
                prefix={<LockOutlined className="input-icon" />}
                placeholder="再次输入密码"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="register-button"
                loading={loading}
                block
              >
                {loading ? '注册中...' : '立即注册'}
              </Button>
            </Form.Item>

            <div className="register-footer">
              <span>已有账户？</span>
              <Button type="link" onClick={goToLogin}>
                立即登录
              </Button>
            </div>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default Register;